package org.budo.phone.freeswitch;

import java.sql.Timestamp;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
@NoArgsConstructor
public class FreeswitchEslClientImpl extends AbstractFreeswitchEslClient {

    /**
     * 最后收到消息时间，每次收到消息时更新
     */
    private transient Timestamp lastMessageTime;

    public FreeswitchEslClientImpl(String host, Integer port, String password) {
        super(host, port, password);
    }

    /**
     * 连接ESL，如果已连接就直接返回，判断假死重连
     */
    @Override
    public void assertInited() { // 最后消息事件在20秒以前
//        if (Time.when(this.getLastMessageTime()).isBefore(Time.now().minusSecond(20))) {
//            log.error("#68 lastMessageTime=" + this.getLastMessageTime() + ", _eslClient=" + this.getEslClient() + ", set _eslClient=null, init it again");
//            EslUtil.closeQuietly(this.getEslClient()); // 释放旧的资源
//            this.setEslClient(null); // 释放重连
//        }

        // 已连接上
        if (null != this.getEslClient() && this.canSend()) {
            return;
        }

        // 连接
        if (null == this.getEslClient() || !this.canSend()) {
            super.assertInited_1();
        }

        // 没连上
        if (null == this.getEslClient() || !this.canSend()) {
            log.error("#71 getEslClient is null, this=" + this);
            return;
        }
    }

    @Override
    public String toString() {
        return super.toString() + ", host=" + this.getHost() + ", port=" + this.getPort() //
                + ", password=" + this.getPassword() + ", eslClient=" + this.getEslClient() //
                + ", lastMessageTime=" + this.getLastMessageTime();
    }
}